package com.solidtrust.admin.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solidtrust.admin.service.PriceService;
import com.solidtrust.entity.Che168;
import com.solidtrust.repository.Che168Repository;

/*
 * Che168
 * 
 */
@Deprecated
@Controller
@RequestMapping("price")
public class PriceController {
	
	private static final Integer[] MILEAGE_RANGE = {5000, 20000, 50000, 100000, 150000, 200000, 300000};
	
	@Autowired PriceService service;
	@Autowired Che168Repository rep;

	@RequestMapping("index")
	public String index(
			Model m,
			@RequestParam(value="page", required=false, defaultValue="1") Integer pageIndex, 
			@RequestParam(value="pageSize", required=false, defaultValue="20") Integer pageSize,
			@RequestParam(value="brand", required=false) String brand,
			@RequestParam(value="model", required=false) String model,
			@RequestParam(value="build", required=false) String build,
			@RequestParam(value="mileage", required=false) Integer mileage){
		
		if(brand != null && model != null && build != null){
			Pageable pageable = new PageRequest(pageIndex - 1, pageSize);
			Date from = DateUtils.addMonths(new Date(), -4);
			
			//mileage 
			int start, end;
			if(mileage == 1){
				start = 0;
			}else{
				start = MILEAGE_RANGE[mileage - 2];
			}
			if(mileage == MILEAGE_RANGE.length + 1){
				end = 9999999;
			}else{
				end = MILEAGE_RANGE[mileage - 1];
			}
			Page<Che168> p = rep.findByBrandAndModelAndBuildAndScrapedDateGreaterThanAndMileageBetween(
					pageable, brand, model, build, from, start, end);
			Object[] aggregate = rep.aggregate(brand, model, build, from, start, end);
			
			m.addAttribute("page", p);
			m.addAttribute("aggregate", aggregate);
			m.addAttribute("brand", brand);
			m.addAttribute("model", model);
			m.addAttribute("build", build);
			m.addAttribute("mileage", mileage);
			
		}
		return "admin/price/index.jsp";
	}
	
	@ResponseBody
	@RequestMapping("getCategories")
	public List<String> getCategories(
			@RequestParam(value="brand", required=false) String brand,
			@RequestParam(value="model", required=false) String model,
			@RequestParam(value="level", required=false) Integer level){
		return service.getCategories(brand, model, level);
	}
	
	
	
}
